package com.viewpagertext.utils;

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import com.viewpagertext.Model.DownloadMusic;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

/**
 * 下载音乐
 */
public class FileDownloader extends AsyncTask<String, Void, String> {

    private static final String TAG = "FileDownloader";

    @Override
    protected String doInBackground(String... params) {
        String i_url = params[0];
        String pic = params[1];
        String fileName = params[2];
        String []fileUrlArr = new String[]{i_url, pic};
        String []ab_path = new String[2];
        try {
            int i = 0;
            for (String fileUrl : fileUrlArr){
                URL url = new URL(fileUrl);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                // 设置连接超时时间
                urlConnection.setConnectTimeout(5000);
                // 设置读取超时时间
                urlConnection.setReadTimeout(5000);
                // 连接
                urlConnection.connect();
                // 判断请求是否成功
                if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + urlConnection.getResponseCode()
                            + " " + urlConnection.getResponseMessage();
                }
                // 获取输入流
                InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
                // 指定保存文件的路径为Download/kunjiamusic目录
                File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                File kunjiaMusicDir = new File(downloadDir, "kunjiamusic");
                if (!kunjiaMusicDir.exists()) {
                    kunjiaMusicDir.mkdirs();
                }

                File file;

                if (i == 0){
                    if (fileUrl.contains("mp3")){
                        file = new File(kunjiaMusicDir, fileName + ".mp3");
                    }else {
                        file = new File(kunjiaMusicDir, fileName + ".m4a");
                    }

                }else {
                    // 下载图片
                    file = new File(kunjiaMusicDir, fileName + ".jpg");
                }

                if (file.exists()) {
                    if (!file.delete()){
                        // 如果文件存在但删除失败，处理异常情况
                        Log.e("FileOperation", "Failed to delete existing file: " + file.getAbsolutePath());
                    }
                }
                // 创建输出流
                OutputStream outputStream = new FileOutputStream(file);

                byte data[] = new byte[1024];
                int count;
                while ((count = inputStream.read(data)) != -1) {
                    outputStream.write(data, 0, count);
                }

                // 关闭流
                outputStream.flush();
                outputStream.close();
                inputStream.close();

                ab_path[i] = file.getAbsolutePath();
                System.out.println("absolute: "+ i + ab_path[i]);
                i++;
            }

            System.out.println("absolute music: " + ab_path[0]);
            System.out.println("absolute pic: " + ab_path[1]);
            return ab_path[0] + "#@!" + ab_path[1];

        } catch (IOException e) {
            Log.e(TAG, "Download error: " + e.getMessage());
            return "error" + e.getMessage();
        }
    }

//    @Override
//    protected void onPostExecute(String result) {
//        if (result.startsWith("/")) {
//            // 下载成功
//            Log.i(TAG, "File downloaded: " + result);
//        } else {
//            // 下载失败
//            Log.e(TAG, "Download failed: " + result);
//        }
//    }
}